package com.fingard.dsp.bank.directbank.nnbill01;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directConfig.ActSetItem;
import com.fingard.dsp.bank.directbank.FailCode;
import com.fingard.dsp.bank.directbank.PaymentState;
import com.fingard.dsp.bank.directbank.SendBankRespose;
import com.fingard.dsp.bank.directbank.bankInterface.IRealTime;
import com.fingard.dsp.bank.reqrespobj.single.ReqQrySingle;
import com.fingard.dsp.bank.reqrespobj.single.ReqSingle;
import com.fingard.dsp.bank.reqrespobj.single.RetAtsSingle;
import com.fingard.dsp.bank.reqrespobj.single.detail.RetAtsSglDetail;
import com.fingard.text.StringHelper;
import com.fingard.xml.XmlTextReader;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author Cruise
 *
 * 需求：
 *         1、快钱单笔实时代扣高级版
 *         2、快钱信用卡无卡支付
 *
 */
public class NNBill01RealTime extends NNBill01Base implements IRealTime {
	public RetAtsSingle d_9108_RealTimeRec(ReqSingle p_req9108) throws Exception {
		RetAtsSingle retAts = new RetAtsSingle(p_req9108.reqHeader);
		RetAtsSglDetail tmpRetDetail = new RetAtsSglDetail();

		try {
			ActSetItem actItem = getBankConfig().getActSetItem(p_req9108.singleDetail.recAct, "");
			if (actItem == null) {
				tmpRetDetail.respCode = "0";
				tmpRetDetail.respInfo = "未找到账号" + p_req9108.singleDetail.recAct + "对应的商户配置信息";
				tmpRetDetail.transAmt = p_req9108.singleDetail.payAmount;
				tmpRetDetail.reqSeqID = p_req9108.singleDetail.askNumber;
				tmpRetDetail.transState = PaymentState.FAIL_Payment;
				tmpRetDetail.payInfoCode = FailCode.E9981;

				retAts.writeRetDetail(tmpRetDetail);
				return retAts;
			}

			// 组装请求报文
			StringBuilder sbXml = new StringBuilder();

			sbXml.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
			sbXml.append("<MasMessage xmlns=\"http://www.99bill.com/mas_cnp_merchant_interface\">");
			sbXml.append("<version>1.0</version>");
			sbXml.append("<TxnMsgContent>");
			sbXml.append("<txnType>PUR</txnType>");
			sbXml.append("<interactiveStatus>TR1</interactiveStatus>");
			sbXml.append("<cardNo>" + p_req9108.singleDetail.payAct + "</cardNo>");
			if (p_req9108.singleDetail.cvv2.length() > 0 && p_req9108.singleDetail.expiredDate.length() > 0) {
				SimpleDateFormat sdf = new SimpleDateFormat("MMyy");
				Date date = sdf.parse(p_req9108.singleDetail.expiredDate);
				String expiredDate = sdf.format(date);
				sbXml.append("<expiredDate>" + expiredDate + "</expiredDate>");
				sbXml.append("<cvv2>" + p_req9108.singleDetail.cvv2 + "</cvv2>");
			}
			sbXml.append("<amount>" + p_req9108.singleDetail.payAmount + "</amount>");
			sbXml.append("<merchantId>" + actItem.merchantId + "</merchantId>");
			sbXml.append("<terminalId>" + actItem.termId + "</terminalId>");
			sbXml.append("<cardHolderName>" + p_req9108.singleDetail.payName + "</cardHolderName>");
			sbXml.append("<cardHolderId>" + p_req9108.singleDetail.certNum + "</cardHolderId>");
			sbXml.append("<idType>0</idType>");
			sbXml.append("<entryTime>" + Format.DateTime14Format.format(p_req9108.singleDetail.getPayDateTime())
					+ "</entryTime>");
			sbXml.append("<externalRefNumber>" + p_req9108.singleDetail.askNumber + "</externalRefNumber>");
			sbXml.append("<customerId>" + p_req9108.singleDetail.askNumber + "</customerId>");

			if ("1".equals(p_req9108.singleDetail.realNameFlag)) {
				if ("0".equals(p_req9108.singleDetail.realNameType)) {
					sbXml.append("<spFlag>QTOP</spFlag>");
				} else if ("1".equals(p_req9108.singleDetail.realNameType)) {
					sbXml.append("<spFlag>TOP</spFlag>");
				} else if ("2".equals(p_req9108.singleDetail.realNameType)) {
					sbXml.append("<spFlag>STOP</spFlag>");
				}

                sbXml.append("<ext>" + p_req9108.singleDetail.circPaymentNo + "</ext>");
				if ("1".equals(p_req9108.singleDetail.realNameType)) {
                    String circMchNo = p_req9108.singleDetail.circMchNo;
                    if (StringHelper.isNullOrEmpty(circMchNo)) {
                        circMchNo = getBankConfig().getValueAsString("circMchNo");
                    }
                    sbXml.append("<ext1>" + circMchNo + "</ext1>");
					sbXml.append("<bindType>0</bindType>");
				}
			}
			sbXml.append("<tr3Url/>");
			sbXml.append("<extMap>");
			sbXml.append("<extDate><key>phone</key><value>" + p_req9108.singleDetail.cellPhone + "</value></extDate>");
			if ("2".equals(p_req9108.singleDetail.realNameType)) {
                sbXml.append("<extDate><key>tasknumber</key><value>" + p_req9108.singleDetail.insuPolicyNum + "</value></extDate>");
            }
			sbXml.append("</extMap>");
			sbXml.append("</TxnMsgContent>");
			sbXml.append("</MasMessage>");

			// 请求报文
			String reqXml = sbXml.toString();

			// 提交地址
			String submitUrl = bankFront.getUrl("purchase");

			WriteBankLogStep2(reqXml);

			WriteBankLogLn("提交服务地址：" + submitUrl);

			// 发送快钱并获取返回数据
			SendBankRespose smsResp = SmsPost.sendPost(submitUrl, actItem, reqXml, getCharset());

			WriteBankLogStep3(smsResp);

			// 解析快钱返回
			if (smsResp.connState.length() == 0) {
				// 正确返回报文
				if (smsResp.retMessage.indexOf("<") >= 0) {
					XmlTextReader xmlReader = new XmlTextReader(smsResp.retMessage);
					tmpRetDetail.respCode = "0";

					int countTxnMsgCo = xmlReader.countElement("/MasMessage/TxnMsgContent");

					if (countTxnMsgCo == 0) {
						String errorCode = xmlReader.getFirstText("/MasMessage/ErrorMsgContent/errorCode");
						String errorMessage = xmlReader.getFirstText("/MasMessage/ErrorMsgContent/errorMessage");

						tmpRetDetail.payInfoCode = errorCode;
						if (errorMessage != null && errorMessage.toLowerCase().indexOf("no transaction") >= 0
								&& errorMessage.toLowerCase().indexOf("exists") > 0) {
							tmpRetDetail.transState = errorCode + "+No transaction exists";
							tmpRetDetail.payInfoCode = "No transaction exists";
						} else {
							tmpRetDetail.transState = errorCode;
						}
						tmpRetDetail.respInfo = errorMessage;
						tmpRetDetail.reqSeqID = p_req9108.singleDetail.askNumber;
						tmpRetDetail.transAmt = p_req9108.singleDetail.payAmount;

					} else {
						String interactiveStatus = xmlReader.getFirstText("/MasMessage/TxnMsgContent/interactiveStatus");
						if (interactiveStatus.equals("TR2")) {
							String responseCode = xmlReader.getFirstText("/MasMessage/TxnMsgContent/responseCode");
							tmpRetDetail.payInfoCode = responseCode;
							tmpRetDetail.reqSeqID = xmlReader.getFirstText("/MasMessage/TxnMsgContent/externalRefNumber");
							if (StringHelper.isNullOrEmpty(tmpRetDetail.reqSeqID)) {
								tmpRetDetail.reqSeqID = p_req9108.singleDetail.askNumber;
							}
							tmpRetDetail.outTransID = xmlReader.getFirstText("/MasMessage/TxnMsgContent/refNumber");
							double money = Double.parseDouble(xmlReader.getFirstText("/MasMessage/TxnMsgContent/amount"));
							tmpRetDetail.transAmt = Format.DecimalAmtFormat.format(money);
							tmpRetDetail.transState = responseCode;
							tmpRetDetail.respInfo = xmlReader.getFirstText("/MasMessage/TxnMsgContent/responseTextMessage");
						} else {
							tmpRetDetail.respCode = "-1";
							tmpRetDetail.respInfo = "返回的interactiveStatus:" + interactiveStatus + "不符合预期";
						}
					}
				} else {
					tmpRetDetail.respCode = "-1";
					tmpRetDetail.respInfo = smsResp.retMessage;
				}
			} else if (smsResp.connState.equals(FailCode.E9981)) {
				tmpRetDetail.respCode = "0";
				tmpRetDetail.respInfo = smsResp.retMessage;
				tmpRetDetail.transAmt = p_req9108.singleDetail.payAmount;
				tmpRetDetail.reqSeqID = p_req9108.singleDetail.askNumber;
				tmpRetDetail.transState = PaymentState.FAIL_Payment;
				tmpRetDetail.payInfoCode = smsResp.connState;
			} else {
				tmpRetDetail.respCode = "-1";
				tmpRetDetail.respInfo = smsResp.retMessage;
			}
		} catch (Exception e) {
			tmpRetDetail.respCode = "-1";
			tmpRetDetail.respInfo = e.toString();
			e.printStackTrace();
		}

		if (tmpRetDetail.respCode.equals("-1") && StringHelper.isNullOrEmpty(tmpRetDetail.reqSeqID)) {
			tmpRetDetail.reqSeqID = p_req9108.singleDetail.askNumber;
		}

		retAts.writeRetDetail(tmpRetDetail);
		return retAts;
	}

	public RetAtsSingle d_9144_QryRealTimeRec(ReqQrySingle p_req9144) throws Exception {
		RetAtsSingle retAts = new RetAtsSingle(p_req9144.reqHeader);
		RetAtsSglDetail tmpRetDetail = new RetAtsSglDetail();

		try {
			ActSetItem actItem = getBankConfig().getActSetItem(p_req9144.recAct, "");
			if (actItem == null) {
				tmpRetDetail.respCode = "-1";
				tmpRetDetail.respInfo = "未找到账号" + p_req9144.recAct + "对应的商户配置信息";
				retAts.writeRetDetail(tmpRetDetail);
				return retAts;
			}

			StringBuilder sbXml = new StringBuilder();
			sbXml.append("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>");
			sbXml.append("<MasMessage xmlns=\"http://www.99bill.com/mas_cnp_merchant_interface\">");
			sbXml.append("<version>1.0</version>");
			sbXml.append("<QryTxnMsgContent>");
			sbXml.append("<externalRefNumber>" + p_req9144.askNumber + "</externalRefNumber>");
			sbXml.append("<txnType>PUR</txnType>");
			sbXml.append("<merchantId>" + actItem.merchantId + "</merchantId>");
			sbXml.append("<terminalId>" + actItem.termId + "</terminalId>");
			sbXml.append("</QryTxnMsgContent>");
			sbXml.append("</MasMessage>");

			// 请求报文
			String reqXml = sbXml.toString();

			// 查询地址
			String queryUrl = bankFront.getUrl("queryPurchase");

			WriteBankLogLn("查询服务地址：" + queryUrl);

			WriteBankLogStep2(reqXml);

			// 发送快钱并获取返回
			SendBankRespose smsResp = SmsPost.sendPost(queryUrl, actItem, reqXml, getCharset());

			WriteBankLogStep3(smsResp);

			// 解析快钱返回
			if (smsResp.connState.length() == 0) {
				// 正确返回报文
				if (smsResp.retMessage.indexOf("<") >= 0) {
					XmlTextReader xmlReader = new XmlTextReader(smsResp.retMessage);
					tmpRetDetail.respCode = "0";
					tmpRetDetail.reqSeqID = xmlReader.getFirstText("/MasMessage/QryTxnMsgContent/externalRefNumber");
					tmpRetDetail.transAmt = xmlReader.getFirstText("/MasMessage/TxnMsgContent/amount");
					if(!StringHelper.isNullOrEmpty(tmpRetDetail.transAmt)){
						double money = Double.parseDouble(tmpRetDetail.transAmt);
						tmpRetDetail.transAmt = Format.DecimalAmtFormat.format(money);
					}else{
						tmpRetDetail.transAmt = "";
					}
					String externalRefNumber = xmlReader.getFirstText("/MasMessage/TxnMsgContent/externalRefNumber");
					if (StringHelper.hasAnyChar(externalRefNumber)) {
						tmpRetDetail.reqSeqID = externalRefNumber;
					}
					tmpRetDetail.outTransID = xmlReader.getFirstText("/MasMessage/TxnMsgContent/refNumber");
					String responseCode = xmlReader.getFirstText("/MasMessage/TxnMsgContent/responseCode");
					String responseTextMessage = xmlReader
							.getFirstText("/MasMessage/TxnMsgContent/responseTextMessage");
					String voidFlag = xmlReader.getFirstText("/MasMessage/TxnMsgContent/voidFlag");
					String txnStatus = xmlReader.getFirstText("/MasMessage/TxnMsgContent/txnStatus");

					int countTxnMsgCo = xmlReader.countElement("/MasMessage/TxnMsgContent");

					if (StringHelper.hasAnyChar(responseCode)) {
						tmpRetDetail.transState = responseCode + "+" + voidFlag + "+" + txnStatus;
						tmpRetDetail.payInfoCode = responseCode;
						tmpRetDetail.respInfo = responseTextMessage;
					} else if (countTxnMsgCo == 0) {
						String errorCode = xmlReader.getFirstText("/MasMessage/ErrorMsgContent/errorCode");
						String errorMessage = xmlReader.getFirstText("/MasMessage/ErrorMsgContent/errorMessage");

						tmpRetDetail.payInfoCode = errorCode;
						if (errorMessage != null && errorMessage.toLowerCase().indexOf("no transaction") >= 0
								&& errorMessage.toLowerCase().indexOf("exists") > 0) {
							tmpRetDetail.transState = errorCode + "+No transaction exists";
							tmpRetDetail.payInfoCode = "No transaction exists";
						} else {
							tmpRetDetail.transState = errorCode;
						}
						tmpRetDetail.respInfo = errorMessage;
					} else {
						tmpRetDetail.respCode = "-1";
						tmpRetDetail.respInfo = "返回报文结构不符合预期";
					}
				} else {
					tmpRetDetail.respCode = "-1";
					tmpRetDetail.respInfo = smsResp.retMessage;
				}
			} else {
				tmpRetDetail.respCode = "-1";
				tmpRetDetail.respInfo = smsResp.retMessage;
			}
		} catch (Exception e) {
			tmpRetDetail.respCode = "-1";
			tmpRetDetail.respInfo = e.getMessage();
			e.printStackTrace();
		}

		if (tmpRetDetail.respCode.equals("-1") && StringHelper.isNullOrEmpty(tmpRetDetail.reqSeqID)) {
			tmpRetDetail.reqSeqID = p_req9144.askNumber;
		}

		retAts.writeRetDetail(tmpRetDetail);
		return retAts;
	}
}
